package cn.skycity.framework.service.controller;

import cn.hutool.core.map.MapUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 基于请求转发时的异常处理方式
 */
@Slf4j
@RestController
public class GlobalErrorController extends BasicErrorController {

    public GlobalErrorController(){
        super(new DefaultErrorAttributes(),new ErrorProperties());
    }

    @Override
    @RequestMapping({"","/error"})
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus httpStatus = getStatus(request);
        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        Map<String,Object> map = new HashMap<>();
        map.put("code",httpStatus.value());
        map.put("message", MessageFormat.format("path:{0},error:{1}",MapUtil.getStr(body,"path"),MapUtil.getStr(body,"error")));
        return new ResponseEntity<>(map,HttpStatus.OK);
    }

}
